
#include "stddef.h"
#include "stdbool.h"
#include "stdlib.h"
#include "wl_ext_ringbuffer.h"
#include "wl_ext_mem.h"


#include <stdbool.h>
#include <stdint.h>
#include <string.h>

// 定义环缓存结构体
typedef struct {
    unsigned char* buf;      // 缓存区
    unsigned int size;       // 缓存区大小
    unsigned int head;       // 读指针
    unsigned int tail;       // 写指针
} ring_buffer_hdl_impl;

// 初始化环缓存
void ring_buffer_init(ring_buffer_hdl* hdl, unsigned char* buf, unsigned int size) {
    ring_buffer_hdl_impl* hdl_impl = (ring_buffer_hdl_impl*)malloc(sizeof(ring_buffer_hdl_impl));
    if (!hdl_impl) return;

    *hdl = NULL;

    if (hdl_impl && buf) {
        hdl_impl->buf = buf;
        hdl_impl->size = size;
        hdl_impl->head = 0;
        hdl_impl->tail = 0;

        *hdl = (ring_buffer_hdl)hdl_impl;
    }
}

// 销毁环缓存
void ring_buffer_deinit(ring_buffer_hdl hdl) {
    // 这里实际上不需要做太多，因为缓冲区是传入的，不是动态分配的
    // 如果是动态分配的，需要在这里释放
    ring_buffer_hdl_impl* hdl_impl = (ring_buffer_hdl_impl*)hdl;
    free(hdl_impl->buf);
    free(hdl_impl);
}

// 检查环缓存是否为空
bool ring_buffer_is_empty(ring_buffer_hdl hdl) {
    ring_buffer_hdl_impl* hdl_impl = (ring_buffer_hdl_impl*)hdl;
    return hdl_impl->head == hdl_impl->tail;
}

// 检查环缓存是否已满
bool ring_buffer_is_full(ring_buffer_hdl hdl) {
    ring_buffer_hdl_impl* hdl_impl = (ring_buffer_hdl_impl*)hdl;
    return (hdl_impl->tail + 1) % hdl_impl->size == hdl_impl->head;
}

// 获取环缓存中的元素数量
unsigned int ring_buffer_get_count(ring_buffer_hdl hdl) {
    ring_buffer_hdl_impl* hdl_impl = (ring_buffer_hdl_impl*)hdl;
    if (hdl_impl->tail >= hdl_impl->head) {
        return hdl_impl->tail - hdl_impl->head;
    } else {
        return hdl_impl->size - hdl_impl->head + hdl_impl->tail;
    }
}

// 向环缓存写入数据
unsigned int ring_buffer_write(ring_buffer_hdl hdl, const unsigned char* data, unsigned int count) {
    if (!hdl || !data) return 0;

    ring_buffer_hdl_impl* hdl_impl = (ring_buffer_hdl_impl*)hdl;

    unsigned int available_space = hdl_impl->size - ring_buffer_get_count(hdl_impl);
    if (count > available_space) count = available_space;

    for (unsigned int i = 0; i < count; ++i) {
        hdl_impl->buf[hdl_impl->tail] = data[i];
        hdl_impl->tail = (hdl_impl->tail + 1) % hdl_impl->size;
    }

    return count;
}

// 从环缓存读取数据
unsigned int ring_buffer_read(ring_buffer_hdl hdl, unsigned char* data, unsigned int count) {
    if (!hdl || !data) return 0;
    ring_buffer_hdl_impl* hdl_impl = (ring_buffer_hdl_impl*)hdl;

    unsigned int available_data = ring_buffer_get_count(hdl_impl);
    if (count > available_data) count = available_data;

    for (unsigned int i = 0; i < count; ++i) {
        data[i] = hdl_impl->buf[hdl_impl->head];
        hdl_impl->head = (hdl_impl->head + 1) % hdl_impl->size;
    }

    return count;
}